package cn.liontalk.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author ZhouZhe
 * @version 1.0
 * @description
 * @date 2019-04-17 21:42
 **/
@RestController
public class ServerController {


    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    RestTemplate restTemplate;

    @GetMapping(value = "/getProduct")
    public String msg() {
        // 第一中方式使用 RestTemplate + url 写死
        // RestTemplate restTemplate = new RestTemplate();
        // return restTemplate.getForObject("http://localhost:1300/product",String.class);

//        第二种方式 利用(loadBalancerClient通过应用名获取url,在使用RestTemplate)
//        RestTemplate restTemplate = new RestTemplate();
          ServiceInstance serviceInstance = loadBalancerClient.choose("PRODUCT-SERVICE-1300");
//        String url = String.format("http://%s:%s", serviceInstance.getHost(), serviceInstance.getPort() + "/product");
//        return restTemplate.getForObject(url, String.class);

        //  第三种方式使用 @LoadBalanced + RestTemplate + serviceId 写死
        String response = restTemplate.getForObject("http://PRODUCT-SERVICE-1300/product", String.class);
        return response;
    }
}
